/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.check.checkers;

import cn.ac.iie.di.ban.news.server.check.CheckResult;
import cn.ac.iie.di.ban.news.server.check.Checker;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import sun.misc.BASE64Decoder;

/**
 *
 * @author zwlin
 */
public class PlatInfoChecker implements Checker<String, String> {

    @Override
    public CheckResult check(String src, String target) {
        if (null == src || (src = src.trim()).isEmpty()) {
            return new CheckResult();
        }
        String dst;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bt = decoder.decodeBuffer(src);
            dst = new String(bt, "utf-8");
        } catch (IOException e) {
            return new CheckResult("plat info check error, cannot decode base64.because of " + ExceptionUtils.getStackTrace(e));
        }
        JSONArray array;
        try {
            array = JSONArray.parseArray(dst);
        } catch (Exception e) {
            return new CheckResult("plat info check error, cannot parse json array. because of " + ExceptionUtils.getStackTrace(e));
        }
        try {
            for (Object element : array) {
                if (element instanceof JSONObject) {
                    JSONObject obj = (JSONObject) element;
                    if (obj.containsKey("pid") && obj.containsKey("pname")) {
                    } else {
                        throw new Exception();
                    }
                } else {
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            return new CheckResult("plat info check error, json element illegal.");
        }

        return new CheckResult();
    }

}
